<script setup lang="ts">
    import { ref, onMounted, computed } from 'vue';
    import type { EmojiParam, TextBody } from '@/services/type';
    import { MsgEnum } from '@/enums';
    import { userSessionStore } from '@/stores/session';
    import { useChatStore } from '@/stores/chat';
    import { api } from '@/services/api';
    import { ElMessage } from 'element-plus';

    import Emoji from '@/components/Emoji/index.vue';
    import renderReplyContent from '@/utils/renderReplyContent';

    const sessionStore = userSessionStore();
    const chatStore = useChatStore();

    const textareaRef = ref();
    const iptFileRef = ref();
    // 是否禁用，默认禁用
    let isDisabled = ref(true);
    // 选择表情包
    const chooseEmoji = ref(false);
    // 图片信息
    const pic = ref();
    // 最后的光标对象
    const lastEditRange = ref();

    // 当前回复消息
    const currentMsgReply = computed(() => chatStore.currentMsgReply || {});
    
    // 计算展示的回复消息的内容
    const showReplyContent = () => {
        const type = currentMsgReply?.value?.type
        return renderReplyContent(type, (currentMsgReply?.value?.body as TextBody)?.content);
    }
    // 置空回复的消息
    const onClearReply = () => (chatStore.currentMsgReply = {});

    // 打开文件选择框
    const openFileDialog = () => {
        const input = iptFileRef.value;
        input?.click();
    }
    // 获取文本信息
    const getInput: any = () => {
        return textareaRef.value.innerText.trim();
    }
    // 赋值
    const onInput = () => {
        if(getInput() !== '') {
            isDisabled.value = false;
        } else {
            isDisabled.value = true;
        }
    }
    // 监听粘贴内容到输入框事件，对内容进行处理 处理掉复制的样式标签，只拿取文本部分
    const optimizePasteEvent = (e: any) => {
        e.stopPropagation()
        e.preventDefault()
        let text = '', event = (e.originalEvent || e)
        if (event.clipboardData && event.clipboardData.getData) {
            text = event.clipboardData.getData('text/plain')
        } else if (navigator.clipboard && navigator.clipboard.readText) {
            text = navigator.clipboard.readText.toString();
        }
        if (document.queryCommandSupported('insertText')) {
            document.execCommand('insertText', false, text)
        } else {
            document.execCommand('paste', false, text)
        }
    }
    // 阻止换行事件
    const handleKeydown = (e: KeyboardEvent) => {
        if (e.keyCode === 13 && !e.shiftKey) { // 只有当没有同时按下Shift键时才会阻止回车换行
            e.preventDefault();
        }  
    }
    // 选择图片
    const handleChooseImg = async (e: any) => {
        // 1.获取用户选择的文件对象
        const files = e.target.files
        // 2.用户选择了图片(使用选择的图片)
        const file = files[0];
        // 新建 from 对象
        const data = new FormData();
        data.append('file', file);
        // 上传图片
        const response = await api.common.upload(data);
        // 上传成功
        if(response.code === 0) {
            // 获取图片宽高
            pic.value = await getImgWH(file);
            // 图片地址
            pic.value.url = response.data.downloadUrl;
             // 推送消息
            send(MsgEnum.IMAGE, pic.value);
        }
    }
    // 获取图片宽高
    const getImgWH = async (file: File) => {
        const img = new Image()
        const tempUrl = URL.createObjectURL(file)
        img.src = tempUrl;
        return new Promise((resolve, reject) => {
            img.onload = function () {
                resolve({ 
                    width: img.width, 
                    height: img.height, 
                    size: 0,
                    url: tempUrl
                });
            };
            img.onerror = function () {
                // 释放临时URL资源
                URL.revokeObjectURL(tempUrl);
                reject({ 
                    width: 0, 
                    height: 0, 
                    size: 0,
                    url: null
                });
            }
        });
    }
    // 选择表情包
    const handleChooseEmoji = (item: EmojiParam) => {
        // 创建一个img标签（表情）
        let img = document.createElement('img');
        img.src = item.url;
        img.classList.add('image');
        img.classList.add('emoji');
        img.style.verticalAlign = 'middle';
        img.style.marginLeft = "2px";
        img.style.marginRight = "2px";
        if(item.maxHeight) {
            img.style.maxHeight = item.maxHeight;
        }
        if(item.height) {
            img.style.height = item.height;
        }
        if(item.width) {
            img.style.width = item.width;
        }
        if(item.type === 0) {
            let edit = textareaRef.value;
            if(edit) {
                edit.focus();
            }
            let selection = window.getSelection();
            // 如果存在最后的光标对象
            if (lastEditRange.value) {
                // 选区对象清除所有光标
                selection?.removeAllRanges();
                // 并添加最后记录的光标，以还原之前的状态
                selection?.addRange(lastEditRange.value);
                // 获取到最后选择的位置
                let range = selection?.getRangeAt(0);
                // 在此位置插入表情图
                range?.insertNode(img)
                // false，表示将Range对象所代表的区域的起点移动到终点处
                range?.collapse(false)
                // 记录最后的位置
                lastEditRange.value = selection?.getRangeAt(0);
            } else {
                if(edit) {
                    // 将表情添加到可编辑的div中，作为可编辑div的子节点
                    edit?.appendChild(img)
                    // 使用选取对象，选取可编辑div中的所有子节点
                    selection?.selectAllChildren(edit);
                    // 合并到最后面，即实现了添加一个表情后，把光标移到最后面
                    selection?.collapseToEnd()
                }
            }
        }
        chooseEmoji.value = false
    }
    // 发送点击事件
    const sendMsgHandler = () => {
        if(isDisabled.value) {
            return;
        }
        send(MsgEnum.TEXT, { 
            content: textareaRef.value.innerHTML,
            replyMsgId: currentMsgReply.value?.id
        });
    }
    // 发送
    const send = (msgType: MsgEnum, body: any) => {
        // 调用消息发送接口
        api
        .chat
        .sendMessage({
            // 会话ID
            sessionId: sessionStore.currentSession?.session_id, 
            // 接收人用户内码
            receiveUid: sessionStore.currentSessionInfo?.target_user_info?.yhnm,
            // 消息类型
            msgType, 
            // 消息主体信息
            body
        })
        .then(res => {
            if(res.code === 0) {
                // 消息列表新增一条消息
                chatStore.pushMsg(res.data);
                // 重置当前回复的消息
                chatStore.currentMsgReply = {};
                // 清除输入框内容
                textareaRef.value.innerHTML = '';
                // 禁用发送按钮
                isDisabled.value = true;
                // 发完消息就要刷新会话列表，
                // FIXME 如果当前会话已经置顶了，可以不用刷新
                sessionStore.updateSessionLastActiveTime(sessionStore.currentSession.session_id);
            } else {
                ElMessage.error(res.msg);
            }
        }).finally(() => {
            // 滚动到消息列表底部
            chatStore.chatListToBottomAction?.();
        }); 
    }

    onMounted(() => {
        document.addEventListener('click', (event: any) => {
            var vueEmoji = document.getElementById('vueEmoji')
            if (vueEmoji != undefined && vueEmoji != null && !vueEmoji.contains(event.target)) {
                chooseEmoji.value = false;
            }

        },true);

        if(textareaRef.value) {
            textareaRef.value.onclick = () => {
                // 获取选定对象
                let selection = window.getSelection()
                // 设置最后光标对象
                if (selection && selection.rangeCount > 0) {
                    // 记录光标最后点击可编辑div中所选择的位置
                    lastEditRange.value = selection?.getRangeAt(0);
                }
            }
        }
    });

</script>
<template>
    <div class="chat-edit">
        <div class="reply-msg-wrapper" v-show="Object.keys(currentMsgReply).length">
            <span>{{ showReplyContent() }}</span>
            <div class="reply-msg-close" @click="onClearReply">
                <el-icon class="el-icon-close" :size="12"><Close /></el-icon>
            </div>
        </div>
        <div class="chat-content-input">
            <div class="m-input" 
                ref="textareaRef" 
                contenteditable="true"
                @input="onInput"
                @paste="optimizePasteEvent"
                @keydown="handleKeydown"
                @keyup.enter="sendMsgHandler()"
            ></div>
            <div class="app">
                <div class="emoji-btn">
                    <span @click.stop="chooseEmoji = !chooseEmoji">
                        <svg-icon href='#icon-emoji' :class="'emoji-icon'"></svg-icon>
                    </span>
                    <span @click.stop="openFileDialog">
                        <svg-icon href='#icon-picture' :class="'emoji-icon'"></svg-icon>
                    </span>
                    <el-divider direction="vertical"></el-divider>
                    <span 
                        :class="{ 'action': true, 'disabled': isDisabled, 'edit': !isDisabled }" 
                        @click="sendMsgHandler()"
                    >
                        <svg-icon href='#icon-send' width="23px" height="23px"></svg-icon>
                    </span>
                </div>
                <input @change="handleChooseImg" type="file" accept="image/*" ref="iptFileRef" hidden/>
            </div>
            <div id="emoji" class="emoji-wrapper" v-if="chooseEmoji">
                <emoji id="vueEmoji" @choose="handleChooseEmoji"/>
            </div>
        </div>
    </div>
</template>
<style lang="less" scoped>

    .chat-edit {
        margin: 10px;
        & .reply-msg-wrapper {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 4px 12px;
            margin-bottom: 4px;
            font-size: 12px;
            color: #606266;
            word-wrap: break-all;
            white-space: pre-wrap;
            background-color: #f2f3f5;
            border-radius: 12px;
            & .reply-msg-close {
                display: flex;
                cursor: pointer;
                padding: 2px;
                border-radius: 4px;
                &:hover {
                    background-color: #dedfe0;
                }
            }
        }
        & .chat-content-input{
            display: flex;
            -webkit-box-align: center;
            align-items: center;
            min-height: 40px;
            font-size: 14px;
            background-color: #f2f3f5;
            border-radius: 12px;
            padding: 5px;
            position: relative;
            word-break: break-all;
            & .m-input {
                outline: none;
                width: 77%!important;
                border-radius: 4px;
                color: #555;
                display: block;
                line-height: 20px;
                padding: 6px 12px;
                min-height: 20px;
                max-height: 100px;
            }
            & .app {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 0 12px 0 6px;
                & .emoji-btn {
                    display: flex;
                    align-items: center;
                    & .action {
                        transition: all 0.3s ease;
                    }
                    & .action.edit {
                        transform: rotate(40deg);
                        color: red;
                        cursor: pointer;
                    }
                    & .action.disabled:hover {
                        cursor:not-allowed;
                    }
                    & span {
                        cursor: pointer;
                    }
                }
            }
            & .m-input:empty:before {
                content: attr(placeholder);
                position: absolute;
                pointer-events: none;
                -webkit-user-select: none;
                -moz-user-select: none;
                -ms-user-select: none;
                user-select: none;
                color: #8a919f;
            }
        }
    }

    .emoji-wrapper {
        position: absolute;
        margin-top: -235px;
        margin-left: 80px;
        z-index: 2001;
    }

    .emoji-icon {
        width: 30px!important;
        height: 30px!important;
        color: #707070;
        display: flex;
        align-items: center;
    }

</style>